﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace A2DFramework.HttpLoadBalancer.Utility
{
    public static class SocketHelper
    {
        public static int maxBufferBytes = 999999;

        public static string GetRequestString(Socket socket)
        {
            byte[] data = ReadRequestBytes(socket, maxBufferBytes);
            return System.Text.Encoding.UTF8.GetString(data);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="maxBytes"></param>
        /// <returns></returns>
        public static byte[] ReadRequestBytes(Socket socket, int maxBytes)
        {
            try
            {
                if (WaitForRequestBytes(socket) == 0)
                {
                    return null;
                }

                int numBytes = socket.Available;

                if (numBytes > maxBytes)
                {
                    numBytes = maxBytes;
                }

                int numReceived = 0;

                byte[] buffer = new byte[numBytes];

                if (numBytes > 0)
                {
                    numReceived = socket.Receive(buffer, 0, numBytes, SocketFlags.None);
                }

                if (numReceived < numBytes)
                {
                    byte[] tempBuffer = new byte[numReceived];

                    if (numReceived > 0)
                    {
                        Buffer.BlockCopy(buffer, 0, tempBuffer, 0, numReceived);
                    }

                    buffer = tempBuffer;
                }

                return buffer;
            }
            catch
            {
                return null;
            }
        }

        public static int WaitForRequestBytes(Socket socket)
        {
            int availBytes = 0;

            //try
            //{
                if (socket.Available == 0)
                {
                    socket.Poll(1000, SelectMode.SelectRead);

                    if (socket.Available == 0 && socket.Connected)
                    {
                        socket.Poll(1000, SelectMode.SelectRead);
                    }
                }

                availBytes = socket.Available;
            //}
            //// ReSharper disable EmptyGeneralCatchClause
            //catch
            //// ReSharper restore EmptyGeneralCatchClause
            //{
            //}

            return availBytes;
        }
    }
}
